<template>
  <div>
    <el-card shadow="never" class="d2-mb">
      <el-form class="filter-container" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="品名">
              <el-select
                v-model="CKForm.commodity_name"
                clearable
                placeholder="请选择"
                style="width:100%;"
              >
                <el-option
                  v-for="item in PMNameList"
                  :key="item.commodity"
                  :label="item.commodity"
                  :value="item.commodity"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="敞口类型">
              <el-select
                clearable
                v-model="CKForm.exp_type"
                class="filter-item"
                placeholder="请选择"
              >
                <el-option label="逐笔" value="0"></el-option>
                <el-option label="净敞口" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="方向">
              <el-select
                clearable
                v-model="CKForm.direction"
                class="filter-item"
                placeholder="请选择"
              >
                <el-option label="采购" value="0"></el-option>
                <el-option label="销售" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="合同号">
              <el-input
                placeholder="请输入内容"
                v-model="CKForm.deal_no"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="基准价格">
              <el-select
                v-model="CKForm.base_price_name"
                placeholder="请选择"
                style="width:100%;"
                clearable
              >
                <el-option
                  v-for="item in GzjzNameList"
                  :key="item.base_price_name"
                  :label="item.name"
                  :value="item.base_price_name"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="敞口号">
              <el-input
                placeholder="请输入内容"
                v-model="CKForm.exposure_no"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="部门名称">
              <el-select
                v-model="CKForm.department"
                placeholder="请选择"
                style="width:100%;"
                clearable
              >
                <el-option
                  v-for="item in selectDepartsList"
                  :key="item.department"
                  :label="item.name"
                  :value="item.department"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="4">
            <el-form-item label="业务员">
              <el-input
                placeholder="请输入内容"
                v-model="CKForm.salesman"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-col> -->
          <el-col :span="4">
            <el-form-item label="仓库">
              <el-input
                placeholder="请输入内容"
                v-model="CKForm.depot"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="品牌">
              <el-input
                placeholder="请输入内容"
                v-model="CKForm.brand"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="规格">
              <el-input
                placeholder="请输入内容"
                v-model="CKForm.standard"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="产地">
              <el-input
                placeholder="请输入内容"
                v-model="CKForm.origin"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="日期">
              <el-col :span="11">
                <el-date-picker
                  type="date"
                  placeholder="选择日期"
                  v-model="CKForm.startDate"
                  value-format="yyyy-MM-dd"
                  style="width: 100%;"
                  :picker-options="pickerOptionsStart"
                ></el-date-picker>
              </el-col>
              <el-col class="line tc" :span="2">~</el-col>
              <el-col :span="11">
                <el-date-picker
                  type="date"
                  placeholder="选择日期"
                  v-model="CKForm.endDate"
                  value-format="yyyy-MM-dd"
                  style="width: 100%;"
                  :picker-options="pickerOptionsEnd"
                ></el-date-picker>
              </el-col>
            </el-form-item>
          </el-col>
          <el-col :span="2" style="margin-top:4px;">
            <el-button type="primary" size="small" style='margin-top:3px;' @click="XHCKChange">
              <d2-icon name="search" /> 查询
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <div class="mb">
      <el-button type="default" size="mini" @click="handleFilter_addCkgl">
        <d2-icon name="plus" />
        新增
      </el-button>
      <el-upload
        class="upload-btn"
        :action="uploadUrl"
        accept=".xls, .xlsx"
        :on-success="handleAvatarSuccess"
        :on-progress="uploadProgress"
        :on-error="handleUploadError"
        :show-file-list="false"
        style="display:inline-block;margin:0 10px;"
      >
        <el-button type="default" size="small">
          <d2-icon name="download" />
          导入
        </el-button>
      </el-upload>
      <el-button type="default" size="mini" @click="handleFilter_editCkgl">
        <d2-icon name="edit" />
        修改
      </el-button>
      <el-button
        type="default"
        size="mini"
        icon="el-icon-delete"
        @click="handleFilter_delCkgl"
      >
        删除
      </el-button>
      <!-- <el-button type="default" size="mini" @click="handleFilter_countCkgl">
          <i class="fa fa-building-o" aria-hidden="true"></i>
          计算
        </el-button> -->
      <el-button type="default" size="mini" @click="handleFilter_copyCkgl">
        <i class="fa fa-clipboard" aria-hidden="true"></i>
        复制
      </el-button>
      <el-button type="default" size="mini" @click="handleFilter_affirm">
        <i class="fa fa-check-square-o" aria-hidden="true"></i>
        确认
      </el-button>
      <el-button type="default" size="mini" @click="handleFilter_Noaffirm">
        <i class="fa fa-times-circle-o" aria-hidden="true"></i>
        取消确认
      </el-button>
      <el-button type="default" size="mini" @click="handleFilter_hc">
        <i class="fa fa-calendar-o" aria-hidden="true"></i>
        红冲
      </el-button>
      <el-button type="default" size="mini" @click="handleFilter_hcList">
        <i class="fa fa-calendar-plus-o" aria-hidden="true"></i>
        红冲记录
      </el-button>
      <!-- <a :href="exportExcel" target="_blank" style="margin:0 10px;"> -->
      <el-button type="default" size="mini" @click="Export_fn()">
        <d2-icon name="upload" />
        导出
      </el-button>
      <!-- </a> -->
      <el-button type="default" size="mini" @click="handleFilter_refresh">
        <d2-icon name="refresh" />
        刷新
      </el-button>
    </div>
    <el-card shadow="never" class="d2-mb titleline">
      <template slot="header" style="height:66px;">
        <span class="title_x el-button--primary fl"></span>
        <p class="title_l fl">现货敞口</p>
      </template>
      <div>
        <el-table
          :data="XHCKList"
          style="width: 100%"
          ref="multipleTable"
          border
          :header-cell-style="{ background: '#eef1f6','text-align': 'center' }"
          highlight-current-row
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40" center> </el-table-column>
          <el-table-column type="expand" width="40">
            <template slot-scope="props">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="虚拟购销">
                  <span>{{ props.row.virtual_name }}</span>
                </el-form-item>
                <el-form-item label="期初标识">
                  <span>{{ options1[props.row.begin_flag]["label"] }}</span>
                </el-form-item>
                <el-form-item label="机构名称">
                  <span>{{ props.row.org_name }}</span>
                </el-form-item>
                <el-form-item label="部门名称">
                  <span>{{ props.row.department_name }}</span>
                </el-form-item>
                <el-form-item label="基准价格">
                  <span>{{ props.row.base_price_name }}</span>
                </el-form-item>
                <el-form-item label="币种">
                  <span>{{ props.row.currency_name }}</span>
                </el-form-item>
                <el-form-item label="本币价格">
                  <span>{{ props.row.currency_price }}</span>
                </el-form-item>
                <el-form-item label="汇率">
                  <span>{{ props.row.exchange_rate }}</span>
                </el-form-item>
                <el-form-item label="单价">
                  <span>{{ props.row.unit_price }}</span>
                </el-form-item>
                <el-form-item label="升贴水">
                  <span>{{ props.row.bwd }}</span>
                </el-form-item>
                <el-form-item label="件数">
                  <span>{{ props.row.piece_num }}</span>
                </el-form-item>
                <el-form-item label="每件数量">
                  <span>{{ props.row.piece_vol }}</span>
                </el-form-item>
                <el-form-item label="商品单位">
                  <span>{{ props.row.commodity_unit_name }}</span>
                </el-form-item>
                <el-form-item label="品牌">
                  <span>{{ props.row.brand }}</span>
                </el-form-item>
                <el-form-item label="产地">
                  <span>{{ props.row.origin }}</span>
                </el-form-item>
                <el-form-item label="规格">
                  <span>{{ props.row.standard }}</span>
                </el-form-item>
                <el-form-item label="主属性">
                  <span>{{ props.row.attribute }}</span>
                </el-form-item>
                <el-form-item label="备注">
                  <span>{{ props.row.remark }}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column
            label="确认状态"
            prop="confirm_status" sortable
             width="105"
            :formatter="formatterStatus"
          >
          </el-table-column>
          <el-table-column
            label="是否红冲" sortable
            prop="red_dashed" width="105"
            :formatter="formatterRD"
          >
          </el-table-column>
          <el-table-column
            label="敞口类型"
            prop="exp_type" width="80"
            :formatter="formatterET"
          >
          </el-table-column>
          <el-table-column label="合同号" prop="deal_no"> </el-table-column>
          <el-table-column label="敞口号" prop="exposure_no"> </el-table-column>
          <el-table-column
            label="方向"
            prop="direction" width="60"
            :formatter="formatterDirection"
          >
          </el-table-column>
          <el-table-column label="定价方式" prop="pricing_method_name">
          </el-table-column>
          <el-table-column label="客户名称" prop="customer_name">
          </el-table-column>
          <el-table-column label="品名" prop="name"> </el-table-column>
          <el-table-column label="单据数量" prop="invoice_vol">
          </el-table-column>
          <el-table-column label="敞口数量" prop="exp_vol"> </el-table-column>
          <el-table-column label="定价开始时间" prop="start_date" sortable width="130">
          </el-table-column>
          <el-table-column label="定价结束时间" prop="end_date" sortable width="130">
          </el-table-column>
          <el-table-column label="价格" prop="price"> </el-table-column>
        </el-table>
      </div>
    </el-card>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange1"
      background
      :current-page="CKForm.currentPage"
      :page-size="CKForm.pageSize"
      layout="total, prev, pager, next"
      :total="CKForm.totalPage"
    >
    </el-pagination>
    <!-- 敞口管理-红冲 -->
    <el-dialog title="红冲" class="tc" :visible.sync="handleFilter_hcVisible">
      <el-row>
        <el-table
          :data="HCSJ"
          ref="table1"
          tooltip-effect="dark"
          border
          stripe
          style="width: 93%"
          highlight-current-row
          @current-change="handleCurrentChange"
        >
          <el-table-column
            label="序号"
            type="index"
            width="60"
            align="center"
          ></el-table-column>
          <el-table-column label="日期" align="center" prop="start_date">
            <!-- <template>
                  <el-cascader prop="start_date" class="start_date" :options="post_options" :show-all-levels="false" @change="test" disabled></el-cascader>
                </template> -->
          </el-table-column>
          <el-table-column label="单据数量" prop="invoice_vol">
            <!-- <template>
                  <el-input class="invoice_vol" disabled></el-input>
                </template> -->
          </el-table-column>
          <el-table-column label="调整后单据数量" align="center">
            <template slot-scope="scope">
              <el-input
                class="adjust_vol"
                v-model="scope.row.adjust_vol"
                @input="num_vol"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="差额" prop="shortfall">
            <!-- <template slot-scope="scope"> -->
            <!-- <el-input class="shortfall" v-model="scope.row.shortfall" disabled></el-input> -->
            <!-- </template> -->
          </el-table-column>
        </el-table>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleFilter_hcVisible = false">取消</el-button>
        <el-button type="primary" @click="hcChange">保存</el-button>
      </div>
    </el-dialog>
    <!-- 敞口管理-红冲记录 -->
    <el-dialog
      title="红冲历史"
      class="tc"
      :visible.sync="handleFilter_hcListVisible"
    >
      <el-row>
        <el-table
          :data="HCList"
          ref="table"
          tooltip-effect="dark"
          border
          stripe
          style="width: 93%"
        >
          <el-table-column
            label="序号"
            type="index"
            width="60"
            align="center"
          ></el-table-column>
          <el-table-column
            label="日期"
            align="center"
            prop="date"
          ></el-table-column>
          <el-table-column
            label="单据数量"
            prop="invoice_vol"
          ></el-table-column>
          <el-table-column
            label="调整后单据数量"
            align="center"
            prop="adjust_vol"
          ></el-table-column>
          <el-table-column label="差额" prop="shortfall"></el-table-column>
        </el-table>
      </el-row>
      <el-row> </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleFilter_hcListVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 导入-敞口弹框 -->
    <el-dialog
      title="导入敞口数据"
      class="tc"
      :visible.sync="drCKdialogVisible"
      style="width:100%"
    >
      <el-row>
        <el-table
          :data="drCKtableData"
          ref="table"
          tooltip-effect="dark"
          border
          stripe
          style="width: 100%"
          :row-class-name="tableRow"
          :cell-style="{ 'text-align': 'center' }"
          :header-cell-style="{ 'text-align': 'center' }"
          @selection-change="selectRow"
          highlight-current-row
        >
          <el-table-column
            type="selection"
            width="30"
            align="center"
          ></el-table-column>
          <el-table-column
            label="序号"
            type="index"
            width="60"
            align="center"
          ></el-table-column>
          <el-table-column
            label="部门名称"
            align="center"
            prop="department"
          ></el-table-column>
          <el-table-column
            label="客户名称"
            align="center"
            prop="customer"
          ></el-table-column>
          <el-table-column
            label="币种"
            align="center"
            prop="currency"
          ></el-table-column>
          <el-table-column
            label="方向"
            align="center"
            prop="direction"
          ></el-table-column>
          <el-table-column
            label="虚拟购销"
            align="center"
            prop="virtual"
          ></el-table-column>
          <el-table-column
            label="期初标识"
            align="center"
            prop="begin_flag"
          ></el-table-column>
          <el-table-column
            label="敞口类型"
            align="center"
            prop="exp_type"
          ></el-table-column>
          <el-table-column
            label="定价方式"
            prop="pricing_method"
          ></el-table-column>
          <el-table-column
            label="合同号"
            align="center"
            prop="deal_no"
          ></el-table-column>
          <el-table-column label="品名ID" prop="commodity"></el-table-column>
          <el-table-column label="仓库" prop="depot"></el-table-column>
          <el-table-column
            label="单据数量"
            prop="invoice_vol"
          ></el-table-column>
          <el-table-column label="敞口数量" prop="exp_vol"></el-table-column>
          <el-table-column
            label="定价开始日期"
            prop="start_date"
          ></el-table-column>
          <el-table-column label="基准价格" prop="base_price"></el-table-column>
          <!-- <el-table-column label="估值基准" prop="base_valuation"></el-table-column> -->
          <el-table-column label="汇率" prop="exchange_rate"></el-table-column>
          <el-table-column label="单价" prop="unit_price"></el-table-column>
          <el-table-column label="升贴水" prop="bwd"></el-table-column>
          <el-table-column label="价格" prop="price"></el-table-column>
          <el-table-column
            label="本币价格"
            prop="currency_price"
          ></el-table-column>
          <el-table-column label="件数" prop="piece_num"></el-table-column>
          <el-table-column label="每件数量" prop="piece_vol"></el-table-column>
          <el-table-column
            label="定价结束日期"
            prop="end_date"
          ></el-table-column>
          <el-table-column label="备注" prop="remark"></el-table-column>
        </el-table>
      </el-row>
      <el-row> </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="drCK">上传数据</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 20%;
}
</style>
<script>
import {
  conExposure,
  addExposure,
  conspotreddashed,
  addspotreddashed,
  calculate,
  conspotCap,
  addspotCap,
  conPriceitem,
  conCommodity,
  conExposureExcel
} from "../../../../../api/url_lcc";
import { getDepartments } from "../../../../../api/url";
export default {
  name: "gl_open",
  data() {
    return {
      // 导出
      exportExcel: "",
      // 导入
      uploadUrl: `/user/lead/`,
      drCKtableData: [],
      GzjzNameList: [],
      HCList: [],
      drCKdialogVisible: false,
      // CKForm:{},
      XHCKList: {
        settlement_status:"",
        confirm_status:"",
      },
      PMNameList: [],
      selectlistRow: [],
      rowNum: 1,
      activeName: "first",
      CKForm: {
        page: 1, //当前页
        pageSize: 20,
        totalPage: 1,
        commodity_name: "",
        exp_type: "",
        direction: "",
        deal_no: "",
        direction: "",
        base_price_name: "",
        startDate: "",
        endDate: "",
        department_name: "",
        exposure_no: "",
        salesman: "",
        depot: "",
        brand: "",
        origin: "",
        depot: "",
        standard: ""
      },
      options: [
        {
          value: "0",
          label: "吨"
        },
        {
          value: "1",
          label: "千克"
        },
        {
          value: "2",
          label: "桶"
        },
        {
          value: "3",
          label: "立方米"
        },
        {
          value: "4",
          label: "张"
        },
        {
          value: "5",
          label: "克"
        }
      ],
      options1: [
        {
          value: "0",
          label: "否"
        },
        {
          value: "1",
          label: "是"
        },
        {
          value: "2",
          label: "其他(前期错误导致，请忽略或删除)"
        }
      ],
      // 1.敞口管理
      // 红冲
      handleFilter_hcVisible: false,
      // 红虫历史
      handleFilter_hcListVisible: false,
      // ///////////////////////////////时间限制
      pickerOptionsStart: {
        disabledDate: time => {
          let endDateVal = this.CKForm.endDate;
          if (endDateVal) {
            return time.getTime() > new Date(endDateVal).getTime();
          }
        }
      },
      pickerOptionsEnd: {
        disabledDate: time => {
          let beginDateVal = this.CKForm.startDate;
          if (beginDateVal) {
            return (
              time.getTime() <
              new Date(beginDateVal).getTime() - 1 * 24 * 60 * 60 * 1000
            );
          }
        }
      }
    };
  },
  created() {
    this.tabledatas = [
      { title: "标题1", text: "s111sssa" },
      { title: "标题2", text: "ss222ssa" }
    ];
    this.tabledatas.map(i => {
      i.show = false;
      return i;
    });
    let params = {
      page: 1, //当前页
      pageSize: 20,
      totalPage: 1,
      commodity_name: this.CKForm.commodity_name || "",
      exp_type: this.CKForm.exp_type || "",
      deal_no: this.CKForm.deal_no || "",
      direction: this.CKForm.direction || "",
      base_price_name: this.CKForm.base_price_name || "",
      startDate: this.CKForm.startDate || "",
      endDate: this.CKForm.endDate || "",
      department_name: this.CKForm.department_name || "",
      exposure_no: this.CKForm.exposure_no || "",
      salesman: this.CKForm.salesman || "",
      brand: this.CKForm.brand || "",
      origin: this.CKForm.origin || "",
      depot: this.CKForm.depot || "",
      standard: this.CKForm.standard || "",
      type_name: "spot_exposure"
    };
    var params1 = qs.stringify(params);
    // console.log(1,params1)
    this.exportExcel = "http://192.168.1.50:8005/user/spot_exposure?" + params1;
  },
  computed: {
    computedSiteType() {
      return function(id) {
        return this.options[id]["label"];
      };
    },
    computedSitebeginFlag() {
      return function(id) {
        return this.options1[id]["label"];
      };
    }
  },

  methods: {
    Export_fn() {
      var datas = {
        // commodity_name: "",
        // exp_type: "",
        // direction: "",
        // deal_no: "",
        // base_price_name: "",
        // startDate: "",
        // endDate: "",
        // department_name: "",
        // exposure_no: "",
        // salesman: "",
        // depot: "",
        // brand: "",
        // origin: "",
        // depot: "",
        // standard: "",
        type_name: "spot_exposure"
      };
      conExposureExcel(datas).then(res => {
        let list_name = "敞口管理";
        this.export_excel_file(res, list_name);
      });
    },
    export_excel_file(export_data, list_name) {
      let link = document.createElement("a");
      //    type就是blob的type,是MIME类型的，可以自己查看MIME类型都有哪些
      let blogw = new Blob([export_data], {type: "application/vnd.ms-excel"});
      let objectUrl = window.URL.createObjectURL(blogw); //创建一个新的url对象
      link.href = objectUrl;
      let file_name = `${list_name}列表.xlsx`;
      link.download = file_name; //  下载的时候自定义的文件名
      link.click();
      window.URL.revokeObjectURL(objectUrl); //为了更好地性能和内存使用状况，应该在适当的时候释放url.
    },
    // 获取表格选中时的数据
    selectRow(val) {
      this.selectlistRow = val;
    },
    // 敞口导入
    handleAvatarSuccess(res, file) {
      // this.uploadloading.close();
      console.log(444444, res.result);
      if (res && res.errcode === "1") {
        this.$message({
          message: "导入成功",
          type: "success"
        });
        this.drCKdialogVisible = true;
        this.drCKtableData = [];
        var data3 = res.result.Sheet1;
        for (var i = 0; i < data3.length; i++) {
          this.drCKtableData[i] = {
            department: data3[i].部门名称,
            customer: data3[i].客户名称,
            currency: data3[i].币种,
            direction: data3[i].方向,
            virtual: data3[i].虚拟购销,
            begin_flag: data3[i].期初标识,
            exp_type: data3[i].敞口类型,
            pricing_method: data3[i].定价方式,
            deal_no: data3[i].合同号,
            commodity: data3[i].品名ID,
            depot: data3[i].仓库,
            invoice_vol: data3[i].单据数量,
            exp_vol: data3[i].敞口数量,
            start_date: data3[i].定价开始日期,
            base_price: data3[i].基准价格,
            // base_valuation: data3[i].估值基准,
            exchange_rate: data3[i].汇率,
            unit_price: data3[i].单价,
            bwd: data3[i].升贴水,
            price: data3[i].价格,
            currency_price: data3[i].本币价格,
            piece_num: data3[i].件数,
            piece_vol: data3[i].每件数量,
            end_date: data3[i].定价结束日期,
            remark: data3[i].备注
          };
        }
      } else {
        this.$message.error(res.msg);
      }
    },
    // 导入保存
    drCK() {
      console.log("敞口导入选中行数据", this.selectlistRow);
      var drCKtableData = this.selectlistRow;
      drCKtableData.forEach(function(item, index) {
        var data1 = item.exp_type;
        var data2 = item.pricing_method;
        var data3 = item.direction;
        var data4 = item.virtual;
        var data5 = item.begin_flag;
        if (data2 == "一口价") {
          item.pricing_method = "0";
        } else if (data2 == "点价") {
          item.pricing_method = "1";
        } else if (data2 == "均价") {
          item.pricing_method = "2";
        }
        if (data1 == "逐笔") {
          item.exp_type = "0";
        } else if (data1 == "净敞口") {
          item.exp_type = "1";
        }
        if (data3 == "采购") {
          item.direction = "0";
        } else if (data3 == "销售") {
          item.direction = "1";
        }
        if (data4 == "是") {
          item.virtual = "1";
        } else if (data4 == "否") {
          item.virtual = "0";
        }
        if (data5 == "是") {
          item.begin_flag = "1";
        } else if (data5 == "否") {
          item.begin_flag = "0";
        }
      });
      let params = {
        operation: "EXP",
        exp: this.selectlistRow
      };
      calculate(params)
        .then(res => {
          console.log("敞口计算", res.result);
          this.$message.success(res.result);
          this.drCKtableData = [];
          var data1 = res.result;
          for (var i = 0; i < data1.length; i++) {
            this.drCKtableData[i] = {
              pricing_method: data1[i].pricing_method,
              exp_type: data1[i].exp_type,
              deal_no: data1[i].deal_no,
              commodity: data1[i].commodity,
              depot: data1[i].depot,
              invoice_vol: data1[i].invoice_vol,
              exp_vol: data1[i].new_exp_vol,
              start_date: data1[i].start_date,
              base_price: data1[i].base_price,
              base_valuation: data1[i].base_valuation,
              exchange_rate: data1[i].exchange_rate || "0",
              unit_price: data1[i].unit_price || "0",
              bwd: data1[i].bwd || "0",
              price: data1[i].new_price || "0",
              currency_price: data1[i].new_currency_price || "0",
              piece_num: data1[i].piece_num || "0",
              piece_vol: data1[i].piece_vol || "0",
              end_date: data1[i].end_date,
              remark: data1[i].remark
            };
          }
          this.add_ckList();
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    add_ckList() {
      var drCKtableData = [];
      var drCKtableData = this.drCKtableData;
      drCKtableData.forEach(function(item, index) {
        var data1 = item.exp_type;
        var data2 = item.pricing_method;
        var data3 = item.direction;
        var data4 = item.virtual;
        var data5 = item.begin_flag;
        if (data2 == "一口价") {
          item.pricing_method = "0";
        } else if (data2 == "点价") {
          item.pricing_method = "1";
        } else if (data2 == "均价") {
          item.pricing_method = "2";
        }
        if (data1 == "逐笔") {
          item.exp_type = "0";
        } else if (data1 == "净敞口") {
          item.exp_type = "1";
        }
        if (data3 == "采购") {
          item.direction = "0";
        } else if (data3 == "销售") {
          item.direction = "1";
        }
        if (data4 == "是") {
          item.virtual = "1";
        } else if (data4 == "否") {
          item.virtual = "0";
        }
        if (data5 == "是") {
          item.begin_flag = "1";
        } else if (data5 == "否") {
          item.begin_flag = "0";
        }
      });
      let params = {
        operation: "LEAD",
        data: this.drCKtableData
      };
      addExposure(params)
        .then(res => {
          this.$message.success(res.result);
          this.drCKdialogVisible = false;
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },

    // 导出
    exportExcel1() {
      let params = {
        page: 1, //当前页
        pageSize: 20,
        totalPage: 1,
        commodity_name: this.CKForm.commodity_name || "",
        exp_type: this.CKForm.exp_type || "",
        deal_no: this.CKForm.deal_no || "",
        direction: this.CKForm.direction || "",
        base_price_name: this.CKForm.base_price_name || "",
        startDate: this.CKForm.startDate || "",
        endDate: this.CKForm.endDate || "",
        department_name: this.CKForm.department_name || "",
        exposure_no: this.CKForm.exposure_no || "",
        salesman: this.CKForm.salesman || "",
        brand: this.CKForm.brand || "",
        origin: this.CKForm.origin || "",
        depot: this.CKForm.depot || "",
        standard: this.CKForm.standard || "",
        type_name: "spot_exposure"
      };
      // var params1 = JSON.stringify(params);
      // var exportExcel = "http://192.168.1.50:8005/user/spot_exposure" + params1
      window.open(exportExcel, "_self");
      // conExposure(qs.stringify(params)).then(res => {
      //        this.$message.error("下载成功");
      //        var blob = new Blob([res], { type: fileType });
      // // console.log(blob);
      // var a = document.createElement('a');
      // var url = window.URL
      //   ? window.URL.createObjectURL(blob)
      //   : window.webkitURL.createObjectURL(blob);
      // a.href = url;
      // a.download = data.annex_real_name;
      // document.body.appendChild(a);
      // a.click();
      // window.URL.revokeObjectURL(url);
      //      }).catch(err =>{
      //   this.$message.error(err.msg);
      // });
    },
    // ////////////////////////////////////////////////////////////敞口管理
    // 敞口显示
    //  formatterYN(row,column){
    //       return row.status = "0"?'否':'是'
    //   },
    // 确认状态
    formatterStatus(row, column) {
      return row.confirm_status == "0" ? "否" : "是";
    },
    // 是否红冲
    formatterRD(row, column) {
      return row.red_dashed == "0" ? "否" : "是";
    },
    //  基准价格
    // 估值基准
    GzjzNameChange() {
      let params = {
        name: "",
        status: "",
        price_origin: ""
      };
      conPriceitem(params)
        .then(res => {
          this.$message.success(res.result);
          this.GzjzNameList = [];
          var data = res.result;
          for (var i = 0; i < data.length; i++) {
            this.GzjzNameList[i] = {
              base_price_name: data[i]["id"],
              name: data[i]["name"]
            };
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //  部门信息
    //树形结构转换为扁平数组
    treeToList(tree) {
      var queen = [];
      var out = [];
      queen = queen.concat(tree);
      while (queen.length) {
        var first = queen.shift();
        if (first.sub_depart) {
          queen = queen.concat(first.sub_depart);
          delete first["sub_depart"];
        }
        out.push(first);
      }
      return out;
    },
    // 查询部门
    handle_getDepartments() {
      getDepartments()
        .then(res => {
          this.selectDepartsList = [];
          var data1 = res.result;
          var arr = this.treeToList(data1);
          for (var i = 0; i < arr.length; i++) {
            this.selectDepartsList[i] = {
              name: arr[i]["name"],
              department: arr[i]["id"]
            };
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    // 品名
    PMNameChange() {
      let params = {
        category: "",
        name: "",
        commodity_spot__brand: "",
        status: ""
      };
      conCommodity(params)
        .then(res => {
          this.$message.success(res.result);
          this.PMNameList = [];
          var data = res.result;
          for (var i = 0; i < data.length; i++) {
            this.PMNameList[i] = {
              commodity: data[i]["name"],
              commodity_name: data[i]["id"]
            };
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    // 敞口类型逐笔，净敞口
    formatterET(row, column) {
      if (row.exp_type == "0") {
        return "逐笔";
      } else if (row.exp_type == "1") {
        return "净敞口";
      }
    },
    //  方向采购,销售
    formatterDirection(row, column) {
      if (row.direction == "0") {
        return "采购";
      } else if (row.direction == "1") {
        return "销售";
      }
    },
    // JLFormat(row, column) {
    //      if (row.measure_unit === 0) {
    //          return '吨';
    //      } else if (row.measure_unit === 1) {
    //          return '千克';
    //      } else if (row.measure_unit === 2) {
    //          return '桶';
    //      } else if (row.measure_unit === 3) {
    //          return '金属吨';
    //      } else if (row.measure_unit === 4) {
    //          return '风干吨';
    //      } else if (row.measure_unit === 5) {
    //          return '手';
    //      }
    //  },
    // 现货敞口查询
    // 每页数
    handleSizeChange(val) {
      this.CKForm.pageSize = val;
      this.CKForm.page = 1;
      this.XHCKChange1();
    },
    // 当前页
    handleCurrentChange1(val) {
      this.CKForm.page = val;
      this.XHCKChange1();
    },
    XHCKChange() {
      this.CKForm.page = 1;
      this.XHCKChange1();
    },
    XHCKChange1() {
      conExposure(this.CKForm)
        .then(res => {
          // if (res.errcode == "1") {
          this.XHCKList = [];
          this.CKForm.totalPage = res.result.count;
          console.log(1, data);
          //  this.XHCKList = data
          var data = res.result.results;
          for (var i = 0; i <= data.length; i++) {
            this.XHCKList[i] = {
              "settlement_status": data[i]["settlement_status"],
              confirm_status: data[i]["confirm_status"],
              department_name: data[i]["department_name"],
              red_dashed: data[i]["red_dashed"],
              salesman: data[i]["salesman"],
              depot: data[i]["depot"],
              org_name: data[i]["org_name"],
              exp_type: data[i]["exp_type"].toString(),
              deal_no: data[i]["deal_no"],
              pricing_method_name: data[i]["pricing_method_name"],
              exposure_no: data[i]["exposure_no"],
              direction: data[i]["direction"].toString(),
              customer_name: data[i]["customer_name"],
              customer: data[i]["customer"],
              invoice_vol: data[i]["invoice_vol"],
              exp_vol: data[i]["exp_vol"],
              start_date: data[i]["start_date"],
              end_date: data[i]["end_date"],
              department_name: data[i]["department_name"],
              department: data[i]["department"],
              base_valuation: data[i]["base_valuation"],
              exchange_rate: data[i]["exchange_rate"],
              unit_price: data[i]["unit_price"],
              bwd: data[i]["bwd"],
              base_price: data[i]["base_price"],
              piece_num: data[i]["piece_num"],
              piece_vol: data[i]["piece_vol"],
              category: data[i]["category"],
              base_price_name: data[i]["base_price_name"],
              attribute: data[i].commodity.commodity_spot[0]["attribute"],
              brand: data[i].commodity.commodity_spot[0]["brand"],
              id: data[i].commodity.commodity_unit,
              origin: data[i].commodity.commodity_spot[0]["origin"],
              standard: data[i].commodity.commodity_spot[0]["standard"],
              remark: data[i]["remark"],
              currency_price: data[i]["currency_price"],
              commodity: data[i].commodity["id"], //品名ID
              name: data[i].commodity["name"], //品名
              commodity_unit_name: data[i].commodity["commodity_unit_name"],
              base_valuation: data[i]["base_valuation"], //估值基准ID
              base_price: data[i]["base_price"], //定价基准ID
              price: data[i]["price"],
              begin_flag: data[i]["begin_flag"].toString(),
              pricing_method: data[i]["pricing_method"].toString(),
              customer: data[i]["customer"],
              currency: data[i]["currency"],
              virtual: data[i]["virtual"].toString(),
              virtual_name: data[i]["virtual_name"],
              currency_name: data[i]["currency_name"]
            };
          }
        })
        .catch(err => {
          console.log('err',err)
          this.$message.error(err.msg);
        });
    },

    // 行内编辑
    handleCellDataChange({ rowIndex, key, value, row }) {
      console.log(rowIndex);
      console.log(key);
      console.log(value);
      console.log(row);
    },
    handleUpload(file) {
      this.$import.xlsx(file).then(({ header, results }) => {
        this.table.columns = header.map(e => {
          return {
            label: e,
            prop: e
          };
        });
        this.table.data = results;
      });
      return false;
    },
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    // 多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log("删除1", this.multipleSelection);
    },
    // 1.敞口管理
    // 新增
    // 新增敞口管理
    handleFilter_addCkgl() {
      this.$router.push({ path: "/add_open" });
    },
    // 删除
    handleFilter_delCkgl() {
      var data = this.multipleSelection;
      var Newdata = [];
      var Newdata1 = [];
      data.forEach(function(item, index) {
        var data1 = item.settlement_status;
        Newdata.push(data1);
      });
      data.forEach(function(item, index) {
        var data2 = item.confirm_status;
        Newdata1.push(data2);
      });
      if (this.multipleSelection == undefined) {
        this.openMessage();
      } else if (Newdata.indexOf(1) == "0" || Newdata1.indexOf(1) == "0") {
        this.$message.error("删除只能选择未确认未结算现货敞口！");
      } else {
        this.delPMList();
      }
    },
    del_message() {
      var data = this.multipleSelection;
      var Newdata = [];
      data.forEach(function(item, index) {
        var data1 = item.exposure_no;
        Newdata.push(data1);
        console.log(90, data1, 91, Newdata);
      });
      let params = {
        operation: "DEL",
        spot_exposure: Newdata
      };
      addExposure(params)
        .then(res => {
          this.$message.success(res.result);
          this.XHCKChange();
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    // 删除提示信息
    delPMList() {
      this.$confirm("是否删除数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.del_message();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 确认
    handleFilter_affirm() {
      if (this.multipleSelection == undefined) {
        this.openMessage();
      } else {
        this.$confirm("是否确认数据?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            var data = this.multipleSelection;
            var Newdata = [];
            data.forEach(function(item, index) {
              var data1 = item.exposure_no;
              Newdata.push(data1);
              console.log(90, data1, 91, Newdata);
            });
            let params = {
              operation: "STATUS",
              spot_exposure: Newdata
            };
            addExposure(params)
              .then(res => {
                this.$message.success(res.result);
                this.XHCKChange();
              })
              .catch(err => {
                this.$message.error(err.msg);
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消确认"
            });
          });
      }
    },
    // 取消确认
    handleFilter_Noaffirm() {
      console.log(111, this.multipleSelection[0].red_dashed == "0");
      if (this.multipleSelection == undefined) {
        this.openMessage();
      } else if (this.multipleSelection[0].red_dashed == "1") {
        this.$message.error("红冲过的数据无法取消确认状态！");
      } else {
        this.$confirm("是否取消确认数据?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            var data = this.multipleSelection;
            var Newdata = [];
            data.forEach(function(item, index) {
              var data1 = item.exposure_no;
              Newdata.push(data1);
              console.log(90, data1, 91, Newdata);
            });
            let params = {
              operation: "STATUS",
              spot_exposure: Newdata
            };
            addExposure(params)
              .then(res => {
                this.$message.success(res.result);
                this.XHCKChange();
              })
              .catch(err => {
                this.$message.error(err.msg);
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消取消确认"
            });
          });
      }
    },
    // 多选提示
    openMessage() {
      this.$message({
        dangerouslyUseHTMLString: true,
        type: "error",
        message: "<strong>请勾选你要选择的行，再进行操作！</strong>"
      });
    },
    // 修改
    handleFilter_editCkgl() {
      var data = this.multipleSelection;
      if (this.multipleSelection == undefined) {
        this.openMessage();
      } else if (this.multipleSelection.length != 1) {
        this.$message.error("修改只能选中一条数据进行！");
      } else if (
        this.multipleSelection[0].settlement_status == "1" ||
        this.multipleSelection[0].confirm_status == "1"
      ) {
        this.$message.error("修改只能选择一条未确认未结算现货敞口！");
      } else {
        this.$router.push({
          name: "edit_open",
          params: { editList: data, type: "edit" }
        });
      }
    },
    // 红冲
    handleFilter_hc() {
      if (this.multipleSelection == undefined) {
        this.openMessage();
      } else if (this.multipleSelection.length !== 1) {
        this.$message.error("红冲只能选中一条数据进行！");
      } else if (
        this.multipleSelection.settlement_status == "0" ||
        this.multipleSelection.confirm_status == "0"
      ) {
        this.$message.error("红冲只能选择一条已确认已结算现货敞口！");
      } else if (this.multipleSelection[0].confirm_status == "0") {
        this.$message.error("没有确认状态的数据无法进行红冲操作！");
      } else {
        this.handleFilter_hcVisible = true;
        this.HCSJ = this.multipleSelection;
        this.HCSJ.adjust_vol;
        this.require_des;
      }
    },
    num_vol() {
      this.HCSJ[0].shortfall =
        this.HCSJ[0].invoice_vol - this.HCSJ[0].adjust_vol;
    },
    // 保存红冲
    hcChange() {
      if (this.currentRow == undefined) {
        this.openMessage();
      } else {
        let params = {
          operation: "ADD",
          red_dashed: {
            exp_no: this.currentRow.exposure_no,
            date: this.currentRow.start_date,
            invoice_vol: this.currentRow.invoice_vol,
            adjust_vol: this.currentRow.adjust_vol,
            shortfall: this.currentRow.shortfall
          }
        };
        addspotreddashed(params)
          .then(res => {
            this.$message.success(res.result);
            this.handleFilter_hcVisible = false;
            this.XHCKChange();
          })
          .catch(err => {
            this.$message.error(err.msg);
          });
      }
    },
    // 红冲记录
    handleFilter_hcList() {
      console.log("红冲", this.multipleSelection);
      if (this.multipleSelection == undefined) {
        this.openMessage();
      } else if (this.multipleSelection.length != 1) {
        this.$message.error("修改只能选中一条数据进行！");
      } else if (this.multipleSelection[0].red_dashed === 0) {
        this.$message.error("红冲记录只能选中一条已经红冲过的数据进行！");
      } else {
        this.hcjl();
      }
    },
    hcjl() {
      this.handleFilter_hcListVisible = true;
      let params = {
        exp_no: this.multipleSelection[0].exposure_no
      };
      conspotreddashed(params)
        .then(res => {
          this.HCList = [];
          // console.log(2222222312322,res.result)
          // this.$message.success(res.result);
          var data = res.result;
          for (var i = 0; i < data.length; i++) {
            this.HCList[i] = {
              exp_no: data[i].exp_no,
              date: data[i].created_time,
              invoice_vol: data[i].invoice_vol,
              adjust_vol: data[i].adjust_vol,
              shortfall: data[i].shortfall
            };
          }
          console.log("红冲", this.HCList);
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    // 计算
    handleFilter_countCkgl() {
      var data = this.multipleSelection;
      if (this.multipleSelection == undefined) {
        this.openMessage();
      } else {
        this.count_msg();
      }
    },
    count() {
      let params = {
        operation: "EXP",
        exp: this.multipleSelection
      };
      calculate(params)
        .then(res => {
          this.$message.success(res.result);
          this.XHCKList = [];
          var data = res.result;
          for (var i = 0; i < data.length; i++) {
            this.XHCKList[i] = {
              settlement_status: data[i]["settlement_status"],
              confirm_status: data[i]["confirm_status"],
              department_name: data[i]["department_name"],
              red_dashed: data[i]["red_dashed"],
              salesman: data[i]["salesman"],
              depot: data[i]["depot"],
              exp_type: data[i]["exp_type"],
              deal_no: data[i]["deal_no"],
              exposure_no: data[i]["exposure_no"],
              direction: data[i]["direction"],
              customer_name: data[i]["customer_name"],
              customer: data[i]["customer"],
              commodity: data[i]["commodity"],
              invoice_vol: data[i]["invoice_vol"],
              exp_vol: data[i]["new_exp_vol"],
              start_date: data[i]["start_date"],
              end_date: data[i]["end_date"],
              department_name: data[i]["department_name"],
              department: data[i]["department"],
              base_valuation: data[i]["base_valuation"],
              exchange_rate: data[i]["exchange_rate"],
              unit_price: data[i]["unit_price"],
              bwd: data[i]["bwd"],
              base_price: data[i]["base_price"],
              piece_num: data[i]["piece_num"],
              piece_vol: data[i]["piece_vol"],
              category: data[i]["category"],
              base_price_name: data[i]["base_price_name"],
              commodity_name: data[i].commodity["name"],
              attribute: data[i].commodity.commodity_spot[0]["attribute"],
              brand: data[i].commodity.commodity_spot[0]["brand"],
              id: data[i].commodity.commodity_spot[0]["id"],
              origin: data[i].commodity.commodity_spot[0]["origin"],
              standard: data[i].commodity.commodity_spot[0]["standard"],
              remark: data[i]["remark"],
              currency_price: data[i]["new_currency_price"],
              commodity_id: data[i].commodity["id"], //品名ID
              base_valuation: data[i]["base_valuation"], //估值基准ID
              base_price: data[i]["base_price"], //定价基准ID
              price: data[i]["new_price"],
              begin_flag: data[i]["begin_flag"],
              pricing_method: data[i]["pricing_method"],
              customer: data[i]["customer"],
              currency: data[i]["currency"],
              virtual: data[i]["virtual"]
            };
          }
          console.log("新数据", this.ckxhtableData);
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    count_msg() {
      this.$confirm("是否计算价格及敞口数量?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.count();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消计算"
          });
        });
    },
    // 刷新
    handleFilter_refresh() {
      (this.CKForm.commodity_name = ""),
        (this.CKForm.exp_type = ""),
        (this.CKForm.direction = ""),
        (this.CKForm.deal_no = ""),
        (this.CKForm.direction = ""),
        (this.CKForm.base_price_name = ""),
        (this.CKForm.startDate = ""),
        (this.CKForm.endDate = ""),
        (this.CKForm.department_name = ""),
        (this.CKForm.exposure_no = ""),
        (this.CKForm.salesman = ""),
        (this.CKForm.depot = ""),
        (this.CKForm.brand = ""),
        (this.CKForm.origin = ""),
        (this.CKForm.depot = ""),
        (this.CKForm.standard = ""),
        this.XHCKChange();
    },
    // 复制
    handleFilter_copyCkgl() {
      var data = this.multipleSelection;
      if (this.multipleSelection == undefined) {
        this.openMessage();
      } else if (this.multipleSelection.length != 1) {
        this.$message.error("修改只能选中一条数据进行！");
      } else {
        this.$router.push({
          name: "edit_open",
          params: { editList: data, type: "copy" }
        });
      }
    }
  },
  mounted() {
    this.PMNameChange();
    this.GzjzNameChange();
    this.handle_getDepartments();
    this.XHCKChange();
  }
};
</script>
